<script lang="ts">
	import MessageAvatar from "$lib/modules/chat/MessageAvatar.svelte";
	import type { Message } from "$lib/shared/constant/Interface";
	import MessageTimer from "./MessageTimer.svelte";
	import { createEventDispatcher } from "svelte";
	import { marked, Renderer } from "marked"; // Markdown 解析
	import Markdown from "svelte-markdown";
	import CodeWindow from "./CodeWindow.svelte"; // 引入新建的代码窗口组件
	import { onMount } from "svelte";

	let dispatch = createEventDispatcher();

	export let msg: Message;
	export let time: string = "";
	const renderer = new Renderer();

	marked.setOptions({
		breaks: true,
	});

	//替换换行符
	const replaceLineBreak = (content: string) => {
		return content.replace(/\\n/g, "\n");
	};

	// 检查是否包含代码块
	const containsCodeBlock = (content: string) => {
		const codeBlocks = content
			.split("```")
			.filter((_, index) => index % 2 !== 0); // 获取所有代码块
		if (codeBlocks.length > 0) {
			const firstLine = codeBlocks[0].split("\n")[0].trim(); // 获取第一个代码块的第一行
			return firstLine === "mermaid"; // 判断是否为 "mermaid"
		}
		return false;
	};

	// 用于控制显示代码窗口的状态
	let showCodeWindow = false;

	// 加载状态
	let isLoading = false;

	// 处理关闭窗口
	const handleClose = () => {
		console.log("关闭窗口");
		showCodeWindow = false; // 更新状态
		isLoading = false; // 关闭时重置加载状态
	};

	// 处理查看图表点击事件
	const handleViewChartClick = async () => {
		isLoading = true; // 开始加载
		// 模拟异步加载图表
		await new Promise((resolve) => setTimeout(resolve, 1000)); // 模拟 1 秒的加载
		isLoading = false;
		showCodeWindow = !showCodeWindow; // 切换代码窗口显示状态
	};
</script>

<div
	class="message-container"
	class:left-aligned={msg.role === 0}
	class:right-aligned={msg.role === 1}
>
	<!-- 头像 -->
	<div class="avatar">
		<MessageAvatar role={msg.role} />
	</div>

	<!-- 消息气泡 -->
	<div class="bubble {msg.role === 0 ? 'assistant' : 'user'}">
		<Markdown
			source={replaceLineBreak(
				Array.isArray(msg.content)
					? msg.content.join(" ")
					: typeof msg.content === "object"
					? JSON.stringify(msg.content)
					: msg.content
			)}
		/>

		<!-- 如果消息中包含代码块，显示按钮 -->
		{#if containsCodeBlock(msg.content)}
			<button
				on:click={handleViewChartClick}
				disabled={isLoading}
				class="chart-button"
			>
				<!-- <img src="src/lib/assets/chat/images/chart.png" alt="查看图表" class="chart-icon" /> -->
				<i class="fa-solid fa-chart-diagram" />
				<span>查看图表</span>
			</button>
		{/if}
	</div>
</div>

<!-- 如果 showCodeWindow 为 true，显示代码窗口 -->
{#if showCodeWindow}
	<CodeWindow content={msg.content} on:close={handleClose} />
{/if}

<!-- 时间 -->
{#if time}
	<div class="time-container">
		<MessageTimer
			{time}
			on:handleTop={() => {
				dispatch("scrollTop");
			}}
		/>
	</div>
{/if}

<!-- 使用 Font Awesome -->
<link
	rel="stylesheet"
	href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
/>

<style>
	/* 统一左对齐 */
	.message-container {
		display: flex;
		align-items: flex-start;
		gap: 10px;
		margin-bottom: 12px;
		width: 100%;
	}

	/* .left-aligned {
		justify-content: flex-start; 
		flex-direction: row; 
	}

	.right-aligned {
		justify-content: flex-end; 
		flex-direction: row-reverse; 
	} */

	/* 头像 */
	.avatar {
		width: 36px;
		height: 36px;
		border-radius: 50%;
		overflow: hidden;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 消息气泡 */
	.bubble {
		max-width: 70%;
		padding: 12px 16px;
		border-radius: 12px;
		font-size: 14px;
		line-height: 1.5;
		word-wrap: break-word;
		white-space: pre-wrap;
	}
	.chart-button {
		display: flex;
		margin-top: 8px;
		background-color: #d3d3d3;
		border: none;
		padding: 8px 16px;
		cursor: pointer;
		border-radius: 4px;
	}

	/* AI 消息 - 灰色 */
	.assistant {
		background-color: #f3f3f3;
		color: #333;
		border-radius: 12px 12px 12px 0;
	}

	/* 用户消息 - 浅紫色 */
	.user {
		background-color: #e0d5f0;
		color: #333;
		border-radius: 12px 12px 12px 0;
	}

	/* 时间 */
	.time-container {
		text-align: left;
		color: #999;
		font-size: 12px;
		margin-top: 4px;
		margin-left: 46px;
	}

	/* 按钮样式 */
	button {
		margin-top: 8px;
		background-color: #d3d3d3;
		color: white;
		border: none;
		padding: 8px 16px;
		cursor: pointer;
		border-radius: 4px;
	}
	button:hover {
		background-color: #afafaf;
	}
</style>
